<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>商品推荐系统</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名">
            <template #prefix>
              <el-icon>
                <User/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码">
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="register-link">
        没有账号？
        <el-link type="primary" @click="goToRegister">去注册</el-link>
      </div>
    </el-card>

  </div>
</template>

<script>
export default {
  name: 'LoginPage'
}
</script>

<script setup>
import {ref, reactive} from 'vue'
import {useRouter} from 'vue-router'
import {User, Lock} from '@element-plus/icons-vue'
import {userLoginApi} from "@/api/UserApi";
import {ElMessage} from "element-plus";


const router = useRouter()
const loginFormRef = ref(null)

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}]
}

const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
        if (valid) {
          userLoginApi(loginForm.username, loginForm.password)
              .then((res) => {
                /*返回结果res.data
                * res.data.{
                *   code: 1, // 1成功 0失败
                *   msg:     // 错误信息
                *   data:    // 数据：如商品信息
                * }
                * */
                if (res.data.code === 1) {
                  // 登录成功，保存token
                  localStorage.setItem("token", res.data.data.token);                  localStorage.setItem("user", loginForm.username)
                  ElMessage.success('登录成功')
                  setTimeout(() => {
                    router.push('/');
                  }, 1000);

                } else {
                  ElMessage.error('账号或密码错误！！')
                }
              })
        }
      }
  )
}
const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.register-link {
  text-align: center;
}

.login-card {
  width: 400px;
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 30px;
}
</style> 